package im.yangqiang.android.ui.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;


import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import im.yangqiang.android.ui.R;
/**
 * 图片TextView，使用图片代替文字，实现特别的字体效果
 * Created by Carlton on 2016/5/9.
 */
public class ImageTextView extends View
{
    private final boolean DEBUG = true;
    private Paint mTextPaint;
    private String mText;
    private Map<String, Integer> mSrcResource = new HashMap<>();
    private Map<String, Bitmap> mBitmapData = new HashMap<>();
    /**
     * 字符间距
     */
    private float mLetterSpacing;
    private int mContentWidth;
    private int mContentHeight;
    private int mTextWidthDesired;
    private int mTextHeightDesired;

    public ImageTextView(Context context)
    {
        super(context);
        init(null, 0);
    }

    public ImageTextView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        init(attrs, 0);
    }

    public ImageTextView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        init(attrs, defStyle);
    }

    private void init(AttributeSet attrs, int defStyle)
    {
        final TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ImageTextView, defStyle, 0);
        mText = a.getString(R.styleable.ImageTextView_text);
        mLetterSpacing = a.getDimensionPixelSize(R.styleable.ImageTextView_letter_spacing, 0);
        a.recycle();
        if (isInEditMode())
        {
            demo();
        }


        mTextPaint = new Paint();
        mTextPaint.setTextSize(30);
        mTextPaint.setColor(Color.BLACK);
        mTextPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
        mTextPaint.setAntiAlias(true);
        setWillNotDraw(false);
    }

    private void demo()
    {
        mSrcResource.put("0", R.drawable.ic_font_0);
        mSrcResource.put("1", R.drawable.ic_font_1);
        mSrcResource.put("2", R.drawable.ic_font_2);
        mSrcResource.put("3", R.drawable.ic_font_3);
        mSrcResource.put("4", R.drawable.ic_font_4);
        mSrcResource.put("5", R.drawable.ic_font_5);
        mSrcResource.put("6", R.drawable.ic_font_6);
        mSrcResource.put("7", R.drawable.ic_font_7);
        mSrcResource.put("8", R.drawable.ic_font_8);
        mSrcResource.put("9", R.drawable.ic_font_9);
        mSrcResource.put("%", R.drawable.ic_font_percent);
        mSrcResource.put(".", R.drawable.ic_font_dot);


        for (String key : mSrcResource.keySet())
        {
            if (mSrcResource.containsKey(key))
            {
                mBitmapData.put(key, BitmapFactory.decodeResource(getResources(), mSrcResource.get(key)));
            }
        }
    }

    public void setSrcResource(Map<String, Integer> srcResource)
    {
        mSrcResource = srcResource;
        for (String key : mSrcResource.keySet())
        {
            if (mSrcResource.containsKey(key))
            {
                mBitmapData.put(key, BitmapFactory.decodeResource(getResources(), mSrcResource.get(key)));
            }
        }
    }

    public void setSrcBitmap(Map<String, Bitmap> srcBitmap)
    {
        if (null == mBitmapData)
        {
            mBitmapData = new HashMap<>();
        }
        mBitmapData.clear();
        mBitmapData.putAll(srcBitmap);
    }

    public void setText(String text)
    {
        mText = text;
    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        super.onDraw(canvas);
        if (null == mBitmapData)
        {
            return;
        }
        canvas.save();
        final float left = getPaddingLeft() + (mContentWidth - mTextWidthDesired) / 2;
        final float top = getPaddingTop() + (mContentHeight - mTextHeightDesired) / 2;
        float bmpLeft = left;
        float bmpTop = top;
        for (char str : mText.toCharArray())
        {
            if (mBitmapData.containsKey(String.valueOf(str)))
            {
                Bitmap bmp = mBitmapData.get(String.valueOf(str));
                if (null == bmp)
                {
                    continue;
                }
                canvas.drawBitmap(bmp, bmpLeft, bmpTop, mTextPaint);
                bmpLeft += (bmp.getWidth() + mLetterSpacing);
            }
        }
        if (DEBUG)
        {
            mTextPaint.setColor(Color.argb(100, 0, 0, 255));
            canvas.drawRect(left, top, left + mTextWidthDesired, top + mTextHeightDesired, mTextPaint);
            mTextPaint.setColor(Color.argb(100, 255, 255, 0));
            canvas.drawRect(getPaddingLeft(), getPaddingTop(), getPaddingLeft() + mContentWidth, getPaddingTop() + mContentHeight, mTextPaint);
        }
        canvas.restore();
    }

    private float getHeightDesired()
    {
        Iterator<Bitmap> iterator = mBitmapData.values().iterator();
        if (null == mBitmapData || mBitmapData.isEmpty() || !iterator.hasNext())
        {
            return 53;
        }
        return iterator.next().getHeight();
    }

    private int getWidthDesired()
    {
        if (null == mBitmapData || mBitmapData.isEmpty() || !mBitmapData.values().iterator().hasNext())
        {
            return 32 * mText.length();
        }
        int width = 0;
        for (int i = 0; null != mText && i < mText.length(); ++i)
        {
            String key = String.valueOf(mText.charAt(i));
            if (!mBitmapData.containsKey(key))
            {
                continue;
            }
            width += (mBitmapData.get(key).getWidth() + (i == mText.length() - 1 ? 0 : mLetterSpacing));
        }
        return width;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        int paddingLeft = getPaddingLeft();
        int paddingTop = getPaddingTop();
        int paddingRight = getPaddingRight();
        int paddingBottom = getPaddingBottom();

        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int paddingH = paddingLeft + paddingRight;
        int paddingV = paddingTop + paddingBottom;


        mTextWidthDesired = getWidthDesired();
        mTextHeightDesired = (int) getHeightDesired();
        if (widthMode == MeasureSpec.EXACTLY)
        {
            widthSize = MeasureSpec.getSize(widthMeasureSpec);
        } else
        {
            int desired = mTextWidthDesired + paddingH;
            if (widthMode == MeasureSpec.AT_MOST)
            {
                widthSize = Math.min(desired, widthSize);
            }
        }

        if (heightMode == MeasureSpec.EXACTLY)
        {
            heightSize = MeasureSpec.getSize(heightMeasureSpec);
        } else
        {
            int desired = mTextHeightDesired + paddingV;
            if (heightMode == MeasureSpec.AT_MOST)
            {
                heightSize = Math.min(desired, heightSize);
            }
        }
        mContentWidth = widthSize - paddingH;
        mContentHeight = heightSize - paddingV;

        setMeasuredDimension(widthSize, heightSize);
    }
}
